// https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if (root == nullptr) {
            return vector<vector<int>>();
        }

        vector<vector<int>> ans;
        deque<TreeNode*> q;
        int flag = 1;
        q.push_front(root);

        while (!q.empty()) {
            int hSize = q.size();
            vector<int> hNum;

            if (flag) {
                for (int i = 0; i < hSize; i++) {
                    TreeNode* top = q.front();
                    q.pop_front();
                    hNum.emplace_back(top->val);

                    if (top->left) {
                        q.push_back(top->left);
                    }
                    if (top->right) {
                        q.push_back(top->right);
                    }
                }

                ans.emplace_back(hNum);
                flag = 0;
            } else {
                for (int i = 0 ; i < hSize; i++) {
                    TreeNode* back = q.back();
                    q.pop_back();
                    hNum.emplace_back(back->val);

                    if (back->right) {
                        q.push_front(back->right);
                    }
                    if (back->left) {
                        q.push_front(back->left);
                    }
                }
                ans.emplace_back(hNum);
                flag = 1;
            }
        }
        
        return ans;
    }
};